const { PostItem, User, Club, JoinClub } = require("../db");
const { Op, where } = require("sequelize");

// 申请新建社团
exports.applyClub = async (req, res) => {
  const { clubName, clubIntro, clubLogo, head, headPhone, founder } = req.body;
  const { id: userId } = req.user;

  try {
    const club = await Club.create({
      clubName,
      clubIntro,
      clubLogo,
      head,
      headPhone,
      founder,
      statu: 0, // 审核中0,1,2
      memberNums: 0,
    });
    const joinClub = await JoinClub.create({
      clubId: club.dataValues.id,
      userId,
      role: "club_admin",
      statu: 1 //默认加入为管理员
    });
    res.status(200).json({
      status: 200,
      msg: "申请成功",
      data: club,
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "申请失败",
    });
  }
};

/* 
// 申请社团指导老师
exports.applyClubTeacher = async (req, res) => {
  try {
    // 前端传过来的 clubId
    const { clubId } = req.body;
    if(!clubId){
      return res.status(400).send({
        status: 400,
        message: '参数不正确！'
      })
    }
    const { id: userId } = req.user;

    // 关联信息
    const joinClubInfo = await JoinClub.findOne({
      where: { userid: userId, clubId: clubId }
    });

    // 该用户没有相关联的社团
    if (!joinClubInfo) {
      return res.status(404).json({
        status: 404,
        msg: "未找到用户的社团信息！"
      });
    }

    if(joinClubInfo.dataValues.statu === 0){
      return res.send({
        status: 401,
        message: '加入社团审核未通过'
      })
    }

    switch (joinClubInfo.dataValues.role) {
      case 'club_teacher':
        return res.status(400).json({
          status: 400,
          msg: "您已经是该社团的指导老师，请勿重复申请！"
        });

      case 'club_admin':
        return res.status(400).json({
          status: 400,
          msg: "指导老师仅提供给普通成员申请！"
        });

      case 'member':
        // 修改role的值
        joinClubInfo.statu = 1;
        await joinClubInfo.save();

        return res.json({
          status: 200,
          msg: "申请指导老师成功！"
          
        });

      default:
        return res.status(400).json({
          status: 400,
          msg: "无效的用户角色！"
        });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({
      status: 500,
      msg: "服务器错误，请稍后重试！"
    });
  }
}; */

// 获取社团列表
exports.getClubList = async (req, res) => {
  const { clubName, statu, page, pageSize } = req.body;
  console.log(clubName, statu, page, pageSize);
  const { id: userId } = req.user;

  try {
    const clubList = await Club.findAll({
      offset: (page - 1) * pageSize,
      limit: pageSize,
      where: {
        clubName: {
          [Op.like]: `%${clubName}%`,
        },
        statu: {
          [Op.like]: `%${statu}%`,
        },
      },
    });
    const total = await Club.count({
      where: {
        clubName: {
          [Op.like]: `%${clubName}%`,
        },
        statu: {
          [Op.like]: `%${statu}%`,
        },
      },
    });
    res.status(200).json({
      status: 200,
      msg: "获取成功",
      data: clubList,
      total: total,
    });
  } catch (err) {
    console.log(err);
    res.status(500).send("内部服务器错误");
  }
};

// 通过社团审核
exports.passClub = async (req, res) => {
  const { clubId, statu } = req.body;
  const { id: userId } = req.user;
  try {
    const club = await Club.findByPk(clubId);
    if (!club) {
      res.status(404).json({
        status: 404,
        msg: "未找到该社团",
      });
    } else {
      const user = await User.findByPk(userId);
      if (user.role === "jyu_admin") {
        const clubUpdateRes = await club.update({
          statu: statu,
          where: {
            clubId: clubId,
          },
        });
      }
      res.status(200).json({
        status: 200,
        msg: "审核通过",
      });
    }
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "审核失败",
    });
  }
};

// 修改社团信息
exports.updateClub = async (req, res) => {
  const { clubId, clubName, clubIntro, clubLogo, head, headPhone, founder } =
    req.body;
  const { id: userId } = req.user;
  try {
    const club = await Club.findByPk(clubId);
    if (!club) {
      res.status(404).json({
        status: 404,
        msg: "未找到该社团",
      })
    } else {
      const user = await JoinClub.findOne({
        where: {
          clubId,
          userId,
        },
      })
      if (user.dataValues.role === "club_admin") {
        const clubUpdateRes = await Club.update({
          clubName,
          clubIntro,
          clubLogo,
          head,
          headPhone,
          founder,
        }, {
          where: {
            id: clubId,
          },
        })
        res.status(200).json({
          status: 200,
          msg: "修改成功",
        })
      }
      else {
        res.status(403).json({
          status: 403,
          msg: "您不是该社团管理员，无权修改",
        })
      }
    }
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "修改失败",
    });
  }
}

exports.getClubDetail = async (req, res) => {
  const { clubId } = req.body;
  const { id: userId } = req.user;
  try {
    const club = await Club.findByPk(clubId);
    if (!club) {
      res.status(404).json({
        status: 404,
        msg: "未找到该社团",
      });
    } else {
      const joinRes = await JoinClub.findOne({
        where: {
          clubId,
          userId,
        },
      });
      let ifJoin = null;
      if (joinRes) {
        ifJoin = joinRes.dataValues;
      } else {
        ifJoin = false;
      }
      const memberCount = await JoinClub.count({
        where: {
          clubId,
        },
      });
      res.status(200).json({
        status: 200,
        msg: "获取成功",
        data: club,
        memberCount: memberCount,
        ifJoin: ifJoin,
      });
    }
  } catch (err) {
    console.log(err);
    res.status(500).send("内部服务器错误");
  }
};

// 申请加入社团 ?
exports.joinClub = async (req, res) => {
  // identity 标记是 member身份的加入还是 teacher身份的加入
  const { clubId, identity } = req.body;
  console.log(clubId);
  console.log(identity);

  const { id: userId } = req.user;
  try {
    const club = await Club.findByPk(clubId);
    if (!club) {
      res.status(404).json({
        status: 404,
        msg: "未找到该社团",
      });
    } else {
      const ifJoin = await JoinClub.findOne({
        where: {
          clubId,
          userId,
        },
      });
      if (ifJoin) {
        res.status(200).json({
          status: 200,
          msg: "已申请",
        });
      } else {
        let temp
        // member申请
        if (identity === "member") {
          temp = {
            userId,
            clubId,
            role: 'member',
            statu: 0,
          }
        } else {
          // teacher申请
          temp = {
            userId,
            clubId,
            role: 'club_teacher',
            statu: 0,
          }
        }
        const joinRes = await JoinClub.create(temp);
        res.status(200).json({
          status: 200,
          msg: "申请成功",
        });
      }
    }
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "申请失败",
    });
  }
};

exports.getClubJoinPlz = async (req, res) => {
  const { id: clubId, page, pageSize } = req.body;
  try {
    const joinPlz = await JoinClub.findAll({
      limit: pageSize,
      offset: (page - 1) * pageSize,
      include: [{
        model: User,
        attributes: ['avatarUrl', 'username']   // 只保留前端需要的数据
      }],
      where: {
        clubId,
        statu: 0,
      },
    });
    const joinCount = await JoinClub.count({
      where: {
        clubId,
        statu: 0,
      },
    });
    res.status(200).json({
      status: 200,
      msg: "获取成功",
      data: joinPlz,
      joinCount: joinCount,
    });
  } catch (err) {
    console.log(err);
    res.status(500).send("内部服务器错误");
  }
};

// 审核-加入申请
exports.checkJoin = async (req, res) => {
  const { id: joinId } = req.body;
  console.log(joinId);
  const { id: userId } = req.user;
  try {
    const join = await JoinClub.findByPk(joinId);
    if (!join) {
      res.status(404).json({
        statu: 404,
        msg: "未找到该申请",
      });
    } else {
      // const user = await User.findByPk(userId);
      const adUser = await JoinClub.findOne({
        where: {
          clubId: join.dataValues.clubId,
          userId: userId,
          statu: 1
        }
      })
      if (adUser.dataValues.role === "club_admin") {
        const joinUpdateRes = await JoinClub.update({
          statu: 1,
        }, {
          where: {
            id: joinId,
          }
        });
        // const clubNumAdd = await Club.update({
        //   memberNums: sequelize.literal("memberNums + 1"),
        // });
        res.status(200).json({
          status: 200,
          msg: "审核通过",
          // num: clubNumAdd,
        });
      } else {
        res.status(403).json({
          status: 403,
          msg: "权限不足",
        });
      }
    }
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "审核失败",
    });
  }
};
//获取用户加入的社团
exports.getClubByUserId = async (req, res) => {
  const { id: userId } = req.user;
  try {
    const clubInfs = await User.findOne({
      where: { id: userId },
      include: Club,
    });
    const clubInfsRes = clubInfs.dataValues.Clubs.map((item) => ({
      ...item.dataValues,
      role: item.dataValues.JoinClub.role,
      joinStatus: item.dataValues.JoinClub.statu,
      JoinClub: undefined,
    }));
    res.status(200).json({
      status: 200,
      msg: "获取成功",
      data: clubInfsRes,
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "获取失败",
    });
  }
};

// 获取某个社团的所有指导老师  （不包括正在审核的 statu === 0）
exports.getTeacherByClubId = async (req, res) => {

  try {
    // console.log(req.query)
    const allTeacherRes = await JoinClub.findAll({
      where: {
        clubId: req.query.clubId,
        role: 'club_teacher',
        statu: 1
      },
    });

    if (allTeacherRes) {

      // 通过allTeacherRes获得userId 再通过User表查询用户信息
      let allTeacherInfo = []

      const allTeacherId = allTeacherRes.map(item => item.dataValues.userId)
      for (const teacherId of allTeacherId) {
        const teacherInfo = await User.findByPk(teacherId)
        allTeacherInfo.push({
          id: teacherInfo.dataValues.id,
          username: teacherInfo.dataValues.username,
        })
      }
        res.json({
          status: 200,
          msg: "获取成功",
          data: allTeacherInfo,
        })
    }else {
        res.json({
            status: 404,
            msg: '该社团暂无指导老师！'
        })
    }

  } catch (err) {
    console.log(err);
    res.status(500).json({
      status: 500,
      msg: "获取失败",
    });
  }
}

// TODO 返回社团活动相关图片   做轮播图用？
exports.getImgByClubId = async (req, res) => {

  // TODO 需求？ 暂时先随便返回几张图片 后期搞清楚需求之后再进行权限的判断等

  const fs = require('fs')

  try { // 封装图片url数组 从./uploads下获取
    const imgUrlArr = []
    // 获取./uploads目录下的所有文件的路径
    const files = fs.readdirSync('./upload')
    for (const file of files) {
      console.log(file)
      // 确保是图片
      if (file.indexOf('.jpeg') !== -1 || file.indexOf('.png') !== -1) {
        // 动态生成Base URL
        const host = req.get('host') || 'localhost:8080';
        const protocol = req.protocol || 'http';
        const baseUrl = `${protocol}://${host}/uploads`;

        imgUrlArr.push({
          id: file.split('.')[0], // 文件名作为id
          imgUrl: `${baseUrl}/${file}`, // 动态生成URL
        });
      }
      // 只返回5张
      if (imgUrlArr.length > 5) {
        break
      }
    }
    // 返回
    res.send({
      status: 200,
      message: '获取成功！',
      data: imgUrlArr
    })
  } catch (e) {
    console.error(e.message)
    res.status(500).send({
      status: 500,
      message: '服务器内部错误！'
    })
  }
}